package com.elcom.player.network;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.os.AsyncTask;
import android.util.Log;


public class downloadmanager {
	// Member variables
		protected URL mURL;
		protected String mOutputFolder;
		protected int mNumConnections;
		protected String mFileName;
		protected int mFileSize;
		protected int mState;
		protected int mDownloaded;
		protected ArrayList<DownloadParameter> mListDownloadTask;
		//protected ArrayList<DownloadThread> mListDownloadThread;
		// Contants for block and buffer size
		protected static final int BLOCK_SIZE = 4096;
		protected static final int BUFFER_SIZE = 4096;
//		protected static final int BLOCK_SIZE = 256;
//		protected static final int BUFFER_SIZE = 256;
		protected static final int MIN_DOWNLOAD_SIZE = BLOCK_SIZE * 100;
		
		// These are the status names.
	    public static final String STATUSES[] = {"Downloading",
	    				"Paused", "Complete", "Cancelled", "Error"};
		
		// Contants for download's state
		public static final int DOWNLOADING = 0;
		public static final int PAUSED = 1;
		public static final int COMPLETED = 2;
		public static final int CANCELLED = 3;
		public static final int ERROR = 4;
		
	public downloadmanager(URL url, String outputFolder, int numConnections) {
		mURL = url;
		mOutputFolder = outputFolder;
		mNumConnections = numConnections;
		
		// Get the file name from url path
		String fileURL = url.getFile();
		mFileName = fileURL.substring(fileURL.lastIndexOf('/') + 1);
		System.out.println("File name: " + mFileName);
		mFileSize = -1;
		mState = DOWNLOADING;
		mDownloaded = 0;
		mListDownloadTask = new ArrayList<TaskDownload>();
		//mListDownloadThread = new ArrayList<DownloadThread>();
	}
	class DownloadParameter{
		public TaskDownload mTask;
		public int startByte;
		public int endByte;
		public int mId;
	}
	private void log(String ss){
		Log.d("DownloadManager",ss);
	}
	private void error(){
		log("error");
	}
	private class TaskDownload extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			return null;
		}
		
	}
	private void initDownLoad(){

		HttpURLConnection conn = null;
		try {
			// Open connection to URL
			conn = (HttpURLConnection)mURL.openConnection();
			conn.setConnectTimeout(10000);
			
			// Connect to server
			conn.connect();
			
			// Make sure the response code is in the 200 range.
            if (conn.getResponseCode() / 100 != 2) {
                error();
            }
            
            // Check for valid content length.
            int contentLength = conn.getContentLength();
            if (contentLength < 1) {
                error();
            }
			
            if (mFileSize == -1) {
            	mFileSize = contentLength;
            	//stateChanged();
            	System.out.println("File size: " + mFileSize);
            }
               
            // if the state is DOWNLOADING (no error) -> start downloading
            if (mState == DOWNLOADING) {
            	// check whether we have list of download threads or not, if not -> init download
            	if (mListDownloadTask.size() == 0)
            	{  
            		if (mFileSize > MIN_DOWNLOAD_SIZE) {
		                // downloading size for each thread
						int partSize = Math.round(((float)mFileSize / mNumConnections) / BLOCK_SIZE) * BLOCK_SIZE;
						System.out.println("Part size: " + partSize);
						
						// start/end Byte for each thread
						int startByte = 0;
						int endByte = partSize - 1;
						HttpDownloadThread aThread = new HttpDownloadThread(1, mURL, mOutputFolder + mFileName, startByte, endByte);
						mListDownloadThread.add(aThread);
						int i = 2;
						while (endByte < mFileSize) {
							startByte = endByte + 1;
							endByte += partSize;
							aThread = new HttpDownloadThread(i, mURL, mOutputFolder + mFileName, startByte, endByte);
							mListDownloadThread.add(aThread);
							++i;
						}
            		} else
            		{
            			HttpDownloadThread aThread = new HttpDownloadThread(1, mURL, mOutputFolder + mFileName, 0, mFileSize);
						mListDownloadThread.add(aThread);
            		}
            	} 
//            	else { // resume all downloading threads
//            		for (int i=0; i<mListDownloadThread.size(); ++i) {
//            			if (!mListDownloadThread.get(i).isFinished())
//            				mListDownloadThread.get(i).download();
//            		}
//            	}
				// check the current state again
				if (mState == DOWNLOADING) {
					//setState(COMPLETED);
				}
            }
		} catch (Exception e) {
			error();
		} finally {
			if (conn != null)
				conn.disconnect();
		}
	
	}
}
